package com.plian.Tools.file;

import com.plian.Tools.Tools;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

public class FilesUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FilesUtil.class);

    public static List<PageData> UpFiles(MultipartHttpServletRequest request) throws FileNotFoundException {
        // TODO 自动生成的构造函数存根
        // 文件保存
        Map<String, MultipartFile> mp = request.getFileMap();
        List<PageData> files = new ArrayList<>();
        File path = null;

        String encoding = System.getProperty("file.encoding");

        LOGGER.error("encoding" + encoding);
        /**
         * 创建文件夹
         */
        path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        if (mp.size() > 0) {
            for (String key : mp.keySet()) {
                MultipartFile mpf = mp.get(key);
                if (mpf != null) {
                    PageData pdd = new PageData();
                    Date date = new Date();
                    String time = Tools.date2Str(date, "yyyy-MM-dd_HH_mm_ss");
                    if (mpf.getOriginalFilename() != "") {
                        String uuid = UuidUtil.get32UUID();
                        File upload = new File(path.getAbsolutePath(), "uploadFiles/" + uuid);
                        if (!upload.exists()) {
                            upload.mkdirs();
                        }
                        pdd.put("formName", key);
                        pdd.put("name", time + mpf.getOriginalFilename());
                        LOGGER.error("UpFiles" + mpf.getOriginalFilename());
                        pdd.put("size", mpf.getSize());
                        pdd.put("url", upload.getPath());
                        pdd.put("id", uuid);
                        files.add(pdd);
                        try {
                            mpf.transferTo(new File(upload.getPath(), time + mpf.getOriginalFilename()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return files;

    }

    public static List<PageData> upFiles(List<MultipartFile> files) {
        List<PageData> pageDataList = new ArrayList<>();
        try {
            File path = null;

            String encoding = System.getProperty("file.encoding");

            LOGGER.error("encoding" + encoding);
            /**
             * 创建文件夹
             */
            path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }

            for (MultipartFile multipartFile : files) {
                PageData pdd = new PageData();
                Date date = new Date();
                String time = Tools.date2Str(date, "yyyy-MM-dd_HH_mm_ss");
                if (multipartFile.getOriginalFilename() != "") {
                    String uuid = UuidUtil.get32UUID();
                    File upload = new File(path.getAbsolutePath(), "uploadFiles/" + uuid);
                    if (!upload.exists()) {
                        upload.mkdirs();
                    }
                    pdd.put("name", time + multipartFile.getOriginalFilename());
                    LOGGER.error("UpFiles" + multipartFile.getOriginalFilename());
                    pdd.put("size", multipartFile.getSize());
                    pdd.put("url", upload.getPath());
                    pdd.put("id", uuid);

                    pageDataList.add(pdd);
                    try {
                        pdd.put("md5", DigestUtils.md5Hex(multipartFile.getInputStream()));
                        multipartFile.transferTo(new File(upload.getPath(), time + multipartFile.getOriginalFilename()));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageDataList;

    }

    /**
     * 删除文件或文件夹及文件夹下文件
     *
     * @param url
     */
    public static void delFile(String url) {
        File file = new File(url);
        if (file.isFile()) { // 判断是否是文件夹
            file.delete();// 删除
        } else {
            File[] files = file.listFiles(); // 获取文件
            if (files == null) {
                file.delete();// 删除
            } else {
                for (int i = 0; i < files.length; i++) {// 循环
                    delFile(files[i].getAbsolutePath());
                }
                file.delete();// 删除
            }
        }
    }

    /**
     * 文件下载
     *
     * @param name     文件名，包含拓展名
     * @param url      文件保存路径 不包含文件名
     * @param response
     * @throws Exception
     */
    public static void DownFile(String name, String url, HttpServletResponse response)
            throws Exception {

        // 设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        String n = name.substring(19);
        String na = new String(n.getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment;fileName=" + na);
        String separator = File.separator;

        //获取系统编码
        String encoding = System.getProperty("file.encoding");
        LOGGER.info("FilesUtil------>DownFile name:" + name);
        LOGGER.info("FilesUtil------>DownFile url:" + url);
        LOGGER.info("FilesUtil------>DownFile encoding:" + encoding);
        LOGGER.info("FilesUtil------>DownFile n:" + n);
        LOGGER.info("FilesUtil------>DownFile na:" + na);
        // 打开本地文件流
        InputStream inputStream = new FileInputStream(new String((url + separator + name).getBytes("utf-8"), encoding));
        // 激活下载操作
        OutputStream os = response.getOutputStream();
        // 循环写入输出流
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        // 这里主要关闭。
        os.close();
        inputStream.close();
    }

    /**
     * 文件下载
     *
     * @param name     文件名，包含拓展名
     * @param url      文件保存路径 不包含文件名
     * @param response
     * @throws Exception
     */
    public static void DownFile1(String name, String url, HttpServletResponse response)
            throws Exception {

        // 设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        String n = name;
        String na = new String(n.getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment;fileName=" + na);
        String separator = File.separator;
        //获取系统编码
        String encoding = System.getProperty("file.encoding");
        // 打开本地文件流
        InputStream inputStream = new FileInputStream(new String((url + separator + name).getBytes("utf-8"), encoding));
        // 激活下载操作
        OutputStream os = response.getOutputStream();
        // 循环写入输出流
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        // 这里主要关闭。
        os.close();
        inputStream.close();
    }

    public static HashMap<String, String> extMap() {
        HashMap<String, String> map = new HashMap<>();
        map.put(".pdf", "application/pdf");
        map.put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        map.put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        map.put(".doc", "application/msword");
        map.put(".txt", "text/plain");
        map.put(".js", "text/javascript");
        map.put(".jpg", "image/jpeg");

        map.put(".XLS", "application/vnd.ms-excel");
        map.put(".png", "image/png");
        map.put(".mp3", "audio/mpeg");
        map.put(".ppt", "application/vnd.ms-powerpoint");
        return map;
    }

}
